const puppeteer = require('puppeteer');
const file = require('fs');
const yaml = require('js-yaml');
const os = require('os');

let browser  = null;
let noteList = [];

async function delay(time) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve();
        }, time);
    });
}

async function run() {
    const config = await getConfig();
    const platform = os.platform();
    console.log(`platform: ${platform}`);

    let options;
    if (platform === "darwin") {
        options = {
            headless: false,
            defaultViewport: {
                width: 1920,
                height: 1080
            }
        }
    } else {
        options = {
            headless: false,
            defaultViewport: {
                width: 1920,
                height: 1080
            },
            executablePath: config.chromePath ?? ''
        }
    }

    // 启动浏览器
    browser = await puppeteer.launch(options);
    // 打开新页面
    const page = await browser.newPage();
    // 设置缓存选项
    await page.setCacheEnabled(true);
    await page.setUserAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15');
}

async function getConfig() {
    const yamlContent =  file.readFileSync('confing.ymal', {encoding: 'utf-8'});
    return yaml.load(yamlContent);
}

async function getCookies() {
    // 读取缓存里的Cookies信息
    let cookies = {};
    let cookiesString = file.readFileSync('./cache/cookies.json', {encoding: 'utf-8'});
    //cookies不为空
    if (cookiesString.length > 4) {
        cookies = JSON.parse(cookiesString);
    }
    return cookies;
}

async function saveCookies(page) {
     //登录后保存Cookies
     cookies = await page.cookies('https://www.xiaohongshu.com');
     //将cookies保存到文件
     const cookiesString = JSON.stringify(cookies, null, 2);
     file.writeFileSync('./cache/cookies.json', cookiesString);
}

async function runTodo(note) {


    try {

        const urlkw = note.url 
        let pageStat = false; 

        // 打开新页面
        let page = {};
        page = await browser.newPage();
        // 设置缓存选项
        await page.setCacheEnabled(true);
        await page.setUserAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15');
        //cookies绑定级定到page
        const parsedCookies = await getCookies();
        if (parsedCookies.length > 0) {
            //将Cookies加载到页面
            await page.setCookie(...parsedCookies);
        }else{
           
        }

        //启用请求拦截
        await page.setRequestInterception(true); 
        page.on('request',  request => { 
            if(request.url()==="https://apm-fe.xiaohongshu.com/api/data" || request.url()==="https://t2.xiaohongshu.com/api/v2/collect")
            {
                request.abort()
            }else {
                request.continue()
            }
        });

        await page.on('response', async response => {
 
            await saveCookies(page) 
            const config = await getConfig(); 

            // 替换为你要监听的异步请求URL
            if (response.url().includes('https://edith.xiaohongshu.com/api/sns/web/v2/comment/page')) {
                
                if (response.frame() != null) {

                   try {
                           const noteDetail = await page.$eval('#detail-title', element => {
                                return {
                                    title: element.textContent, // 获取元素的文本内容
                                    content: element.nextElementSibling.textContent, // 获取元素的下一个兄弟元素（正文内容元素）的文本内容
                                    url: window.location.href
                                };
                            });  

                            const data = await response.json(); 

                            //加载到最后页
                            if (data.data != null && noteDetail.url != null ) { 
                           
                                let commentData = {}
                                commentData = data.data
                                commentData.note = noteDetail 

                                file.writeFileSync('./abc.json', JSON.stringify(commentData)); 
                                
                                let pageUrl = 'http://m.tikshop.asia/api/keyword/add.html';
                                const resp = await fetch(pageUrl, {
                                    method: 'POST',
                                    headers: {'Content-Type': 'application/json', 'Auth-Token': config.token},
                                    body: JSON.stringify(commentData)
                                });
            
                                //获得响应对象
                                if (resp.ok) {
                                    const respJson = await resp.json()
                                    console.log("评论成功:", respJson)   
                                }else {
                                    console.log("扫码登录", resp)
                                }  
                            }

                            //加载到最后页
                            if (data.data.has_more === false) {  
                            
                                noteNum++; 
                               
                                setTimeout( async ()=>{
                                    const element = await page.$("div.close"); // 使用CSS选择器获取元素
                                    if (element) {
                                        await element.click(); // 点击元素
                                    }


                                    if(noteNum >= 15) {

                                        if(noteList.length===0){
                                            await getNoteList()
                                        }
                                        await page.close(); 
                                        //取出数据
                                        const note = noteList.pop();
                                        //运行主程序
                                        await runTodo(note)
                                    
                                    }

                                   
                                }, 1000)
 
                                console.log("noteNum",noteNum) 
                                
                            }
                    
                   } catch (error) { 

                   
                   }
                    //滚动到div底部
                    await page.evaluate(`function bb () {
                        //设置一个每200毫秒执行一次的定时器
                        setTimeout(function () {
                            const div = document.querySelector('div.note-scroller');
                            div.scrollTop = 0;
                            div.scrollTop = div.scrollHeight * 1.2;
                        }, 1100);
                     }
                     bb();
                    `);
                }
            }
        });

        await page.goto(urlkw, wait_until="networkIdle2"); 
        const keywordNoteList = await page.$$('section>div>a.cover');  
        let   noteNum  = 0; 
        //获取所有列表项  
        for (const note of keywordNoteList) {
            await note.click();  
            await page.waitForNavigation();
        }

    }catch (e){
        console.log(e.message)
    }
} 

async function getNoteList() {
    const pageUrl = 'http://m.tikshop.asia/api/keyword/index.html?p=1';
    const config = await getConfig();   
    const response = await fetch(pageUrl, {
        method: 'GET',
        headers: {'Content-Type': 'application/json', 'Auth-Token': config.token},
    })
    const noteData = await response.json()
    if(noteData.code===1){
        noteList = noteData.data.rows??[];
        console.log("noteList:", pageUrl) 
        console.log("noteList:", noteList.length)
    }else{
        console.log("noteList:", noteData)
    }
}

async function executeAsync() {
    //获取主列表
    await getNoteList();
    //运行浏览器
    await run().then( async  () => {
        //取出数据
        const note = noteList.pop();
        //运行主程序
        await runTodo(note)
    }).catch(
        error => console.error('出错:', error)
    );
}
executeAsync();
